<?php
session_start();
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/includes/functions.php';

// 简单的管理员验证（用户名为admin）
if (!isset($_SESSION['user_id']) || $_SESSION['username'] !== 'admin') {
    header('Location: login.php');
    exit;
}

// 处理价格趋势设置
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['price_trend'])) {
    $trend = $_POST['price_trend'];
    $trend_strength = isset($_POST['trend_strength']) ? (int)$_POST['trend_strength'] : 5;
    
    // 保存到session中，供generateNewPrice函数使用
    $_SESSION['admin_price_trend'] = $trend;
    $_SESSION['admin_price_strength'] = $trend_strength;
    
    // 重定向以避免刷新时重复提交
    header('Location: admin_price_control.php?status=success');
    exit;
}

// 处理价格区间设置
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['price_range'])) {
    $min_price = $_POST['min_price'];
    $max_price = $_POST['max_price'];
    
    $result = updatePriceRangeConfig($min_price, $max_price);
    
    if ($result['success']) {
        header('Location: admin_price_control.php?status=range_success');
    } else {
        header('Location: admin_price_control.php?status=range_error&message=' . urlencode($result['message']));
    }
    exit;
}

// 获取当前价格
$current_price = getCurrentPrice();
$current_round = getCurrentRound();

// 获取当前轮次的价格历史
$stmt = $pdo->prepare("
    SELECT price, timestamp 
    FROM price_history 
    WHERE round_id = ? 
    ORDER BY timestamp DESC 
    LIMIT 50
");
$stmt->execute([$current_round['id']]);
$price_history = array_reverse($stmt->fetchAll());

// 获取交易数据，按时间戳分组
$stmt = $pdo->prepare("
    SELECT 
        DATE_FORMAT(transaction_time, '%Y-%m-%d %H:%i:00') as time_group,
        SUM(quantity) as trade_quantity,
        SUM(CASE WHEN type = 'buy' THEN quantity ELSE 0 END) as buy_quantity,
        SUM(CASE WHEN type = 'sell' THEN quantity ELSE 0 END) as sell_quantity,
        SUM(amount) as trade_volume
    FROM transactions
    WHERE round_id = ?
    GROUP BY time_group
    ORDER BY time_group
");
$stmt->execute([$current_round['id']]);
$trade_data = $stmt->fetchAll();

// 获取价格交易统计
$stmt = $pdo->prepare("
    SELECT 
        ROUND(price, 2) AS price_point,
        SUM(CASE WHEN type = 'buy' THEN quantity ELSE 0 END) AS buy_quantity,
        SUM(CASE WHEN type = 'sell' THEN quantity ELSE 0 END) AS sell_quantity,
        COUNT(CASE WHEN type = 'buy' THEN 1 ELSE NULL END) AS buy_count,
        COUNT(CASE WHEN type = 'sell' THEN 1 ELSE NULL END) AS sell_count
    FROM transactions
    WHERE round_id = ?
    GROUP BY ROUND(price, 2)
    ORDER BY price_point DESC
");
$stmt->execute([$current_round['id']]);
$price_stats = $stmt->fetchAll();

// 获取当前价格趋势设置
$current_trend = $_SESSION['admin_price_trend'] ?? 'random';
$current_strength = $_SESSION['admin_price_strength'] ?? 5;

// 获取当前价格区间配置
$price_range_config = getPriceRangeConfig();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>价格控制 - 管理面板</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .admin-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .admin-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .admin-nav {
            display: flex;
            gap: 15px;
        }
        
        .admin-nav a {
            color: white;
            text-decoration: none;
            padding: 8px 15px;
            border-radius: 5px;
            background: rgba(255,255,255,0.2);
            transition: background 0.3s;
        }
        
        .admin-nav a:hover {
            background: rgba(255,255,255,0.3);
        }
        
        .admin-section {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .admin-section h2 {
            margin-bottom: 20px;
            color: #333;
            border-bottom: 2px solid #4caf50;
            padding-bottom: 10px;
        }
        
        .price-display {
            font-size: 32px;
            font-weight: bold;
            color: #4caf50;
            text-align: center;
            margin: 20px 0;
        }
        
        .price-chart {
            width: 100%;
            height: 400px;
            margin: 20px 0;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #fff;
            padding: 10px;
            box-sizing: border-box;
            position: relative;
        }
        
        .price-chart canvas {
            width: 100% !important;
            height: 100% !important;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 15px;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background: #f8f9fa;
            font-weight: bold;
            color: #333;
        }
        
        tr:hover {
            background: #f5f5f5;
        }
        
        .trend-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
            max-width: 500px;
            margin: 0 auto;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .form-group label {
            font-weight: bold;
            color: #333;
        }
        
        .radio-group {
            display: flex;
            gap: 20px;
        }
        
        .radio-option {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .form-submit {
            background: #4caf50;
            color: white;
            border: none;
            padding: 12px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .form-submit:hover {
            background: #45a049;
        }
        
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .buy-quantity {
            color: #4caf50;
            font-weight: bold;
        }
        
        .sell-quantity {
            color: #f44336;
            font-weight: bold;
        }
        
        .trend-indicator {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 5px;
            font-weight: bold;
            margin-left: 10px;
        }
        
        .trend-up {
            background: #d4edda;
            color: #155724;
        }
        
        .trend-down {
            background: #f8d7da;
            color: #721c24;
        }
        
        .trend-random {
            background: #e2e3e5;
            color: #383d41;
        }
        
        .ws-status {
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .ws-status.success {
            background: #d4edda;
            color: #155724;
        }
        
        .ws-status.error {
            background: #f8d7da;
            color: #721c24;
        }
        
        .ws-status.connecting {
            background: #fff3cd;
            color: #856404;
        }
        
        /* 价格区间设置样式 */
        .current-range-display {
            background: #e3f2fd;
            border: 1px solid #2196f3;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .current-range-display p {
            margin: 0;
            font-size: 16px;
            font-weight: bold;
            color: #1976d2;
        }
        
        .range-form {
            background: white;
            padding: 20px;
            border-radius: 8px;
            border: 1px solid #ddd;
        }
        
        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .form-row .form-group {
            flex: 1;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        
        .form-group input[type="number"] {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .form-group small {
            display: block;
            margin-top: 5px;
            color: #666;
            font-size: 12px;
        }
        
        .range-preview {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .range-preview p {
            margin: 5px 0;
            font-size: 14px;
        }
        
        .range-preview #range-preview {
            font-weight: bold;
            color: #2196f3;
        }
        
        .range-preview #range-width {
            font-weight: bold;
            color: #4caf50;
        }
        
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <div class="admin-header">
            <div>
                <h1>价格控制面板</h1>
                <p>管理员：<?php echo htmlspecialchars($_SESSION['username']); ?></p>
            </div>
            <div class="admin-nav">
                <a href="admin.php">返回管理面板</a>
                <a href="index.php">返回游戏</a>
                <a href="#" onclick="refreshData()">刷新数据</a>
                <a href="logout.php">退出登录</a>
            </div>
        </div>
        
        <?php if (isset($_GET['status'])): ?>
            <?php if ($_GET['status'] === 'success'): ?>
            <div class="alert alert-success">
                价格趋势设置已更新！
            </div>
            <?php elseif ($_GET['status'] === 'range_success'): ?>
            <div class="alert alert-success">
                价格区间配置已更新！
            </div>
            <?php elseif ($_GET['status'] === 'range_error'): ?>
            <div class="alert alert-error">
                价格区间配置更新失败：<?php echo htmlspecialchars($_GET['message'] ?? '未知错误'); ?>
            </div>
            <?php endif; ?>
        <?php endif; ?>
        
        <!-- 当前价格和轮次 -->
        <div class="admin-section">
            <h2>当前价格信息</h2>
            <div class="price-display">
                ¥<?php echo number_format($current_price, 2); ?>
                <span class="trend-indicator trend-<?php echo $current_trend; ?>">
                    <?php 
                    if ($current_trend === 'up') echo '上涨';
                    elseif ($current_trend === 'down') echo '下跌';
                    else echo '随机';
                    ?>
                    (<?php echo $current_strength; ?>%)
                </span>
            </div>
            <p style="text-align: center;">
                当前轮次：第<?php echo $current_round['round_number']; ?>轮 | 
                状态：<?php echo getRoundStatusText($current_round['status']); ?> | 
                结束时间：<?php echo date('H:i:s', strtotime($current_round['end_time'])); ?> | 
                <span id="ws-status" class="ws-status connecting">连接中...</span>
            </p>
            
            <div class="price-chart">
                <canvas id="priceChart"></canvas>
            </div>
        </div>
        
        <!-- 价格趋势设置 -->
        <div class="admin-section">
            <h2>设置价格趋势</h2>
            <form class="trend-form" method="post" action="admin_price_control.php">
                <div class="form-group">
                    <label>价格趋势：</label>
                    <div class="radio-group">
                        <div class="radio-option">
                            <input type="radio" id="trend-up" name="price_trend" value="up" <?php echo $current_trend === 'up' ? 'checked' : ''; ?>>
                            <label for="trend-up">上涨</label>
                        </div>
                        <div class="radio-option">
                            <input type="radio" id="trend-down" name="price_trend" value="down" <?php echo $current_trend === 'down' ? 'checked' : ''; ?>>
                            <label for="trend-down">下跌</label>
                        </div>
                        <div class="radio-option">
                            <input type="radio" id="trend-random" name="price_trend" value="random" <?php echo $current_trend === 'random' ? 'checked' : ''; ?>>
                            <label for="trend-random">随机</label>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="trend-strength">趋势强度 (1-10)：</label>
                    <input type="range" id="trend-strength" name="trend_strength" min="1" max="10" value="<?php echo $current_strength; ?>" oninput="this.nextElementSibling.value = this.value">
                    <output><?php echo $current_strength; ?></output>
                    <small>数值越大，价格波动越明显</small>
                </div>
                
                <button type="submit" class="form-submit">保存设置</button>
            </form>
        </div>
        
        <!-- 价格区间设置 -->
        <div class="admin-section">
            <h2>设置价格区间</h2>
            <div class="current-range-display">
                <p>当前价格区间：¥<?php echo number_format($price_range_config['min_price'], 2); ?> - ¥<?php echo number_format($price_range_config['max_price'], 2); ?></p>
            </div>
            <form class="range-form" method="post" action="admin_price_control.php">
                <input type="hidden" name="price_range" value="1">
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="min-price">最低价格 (¥)：</label>
                        <input type="number" id="min-price" name="min_price" min="0.01" step="0.01" 
                               value="<?php echo $price_range_config['min_price']; ?>" required>
                        <small>最低不能低于 ¥0.01</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="max-price">最高价格 (¥)：</label>
                        <input type="number" id="max-price" name="max_price" min="0.02" step="0.01" 
                               value="<?php echo $price_range_config['max_price']; ?>" required>
                        <small>必须高于最低价格</small>
                    </div>
                </div>
                
                <div class="range-preview">
                    <p>预览区间：<span id="range-preview">¥<?php echo number_format($price_range_config['min_price'], 2); ?> - ¥<?php echo number_format($price_range_config['max_price'], 2); ?></span></p>
                    <p class="range-width">区间宽度：<span id="range-width">¥<?php echo number_format($price_range_config['max_price'] - $price_range_config['min_price'], 2); ?></span></p>
                </div>
                
                <button type="submit" class="form-submit">更新价格区间</button>
            </form>
        </div>
        
        <!-- 价格交易统计 -->
        <div class="admin-section">
            <h2>价格交易统计</h2>
            <table>
                <thead>
                    <tr>
                        <th>价格点</th>
                        <th>买入数量</th>
                        <th>卖出数量</th>
                        <th>买入次数</th>
                        <th>卖出次数</th>
                        <th>买卖比例</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($price_stats as $stat): ?>
                    <tr>
                        <td>¥<?php echo number_format($stat['price_point'], 2); ?></td>
                        <td class="buy-quantity"><?php echo number_format($stat['buy_quantity'], 4); ?></td>
                        <td class="sell-quantity"><?php echo number_format($stat['sell_quantity'], 4); ?></td>
                        <td><?php echo $stat['buy_count']; ?></td>
                        <td><?php echo $stat['sell_count']; ?></td>
                        <td>
                            <?php 
                            $total = $stat['buy_count'] + $stat['sell_count'];
                            if ($total > 0) {
                                $buy_percentage = round(($stat['buy_count'] / $total) * 100);
                                echo $buy_percentage . '% / ' . (100 - $buy_percentage) . '%';
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@1.0.0/dist/chartjs-adapter-moment.min.js"></script>
    <script>
        // WebSocket连接
        let ws = null;
        let reconnectAttempts = 0;
        const maxReconnectAttempts = 5;
        
        function connectWebSocket() {
            try {
                ws = new WebSocket('ws://154.92.15.189:8080');
                
                ws.onopen = function(event) {
                    console.log('WebSocket连接已建立');
                    reconnectAttempts = 0;
                    
                    // 显示连接状态
                    updateConnectionStatus('已连接', 'success');
                };
                
                ws.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        
                        if (data.type === 'price_update') {
                            updatePriceDisplay(data.price);
                            updateRoundInfo(data.round, data.status);
                            
                            // 如果图表已初始化，更新图表
                            if (window.priceChart) {
                                // 可以在这里添加新的价格点到图表
                                // updateChart(data);
                            }
                        }
                    } catch (error) {
                        console.error('解析WebSocket消息失败:', error);
                    }
                };
                
                ws.onclose = function(event) {
                    console.log('WebSocket连接已关闭');
                    updateConnectionStatus('连接断开', 'error');
                    
                    // 尝试重连
                    if (reconnectAttempts < maxReconnectAttempts) {
                        reconnectAttempts++;
                        setTimeout(connectWebSocket, 3000);
                        console.log(`尝试重连 (${reconnectAttempts}/${maxReconnectAttempts})`);
                    }
                };
                
                ws.onerror = function(error) {
                    console.error('WebSocket错误:', error);
                    updateConnectionStatus('连接错误', 'error');
                };
                
            } catch (error) {
                console.error('WebSocket连接失败:', error);
                updateConnectionStatus('连接失败', 'error');
            }
        }
        
        function updateConnectionStatus(status, type) {
            const statusElement = document.getElementById('ws-status');
            if (statusElement) {
                statusElement.textContent = status;
                statusElement.className = `ws-status ${type}`;
            }
        }
        
        function updatePriceDisplay(newPrice) {
            const priceElement = document.querySelector('.price-display');
            if (priceElement) {
                // 获取当前趋势信息
                const trendElement = priceElement.querySelector('.trend-indicator');
                const trendInfo = trendElement ? trendElement.outerHTML : '';
                
                priceElement.innerHTML = `¥${parseFloat(newPrice).toFixed(2)} ${trendInfo}`;
            }
        }
        
        function updateRoundInfo(roundNumber, status) {
            const roundInfoElement = document.querySelector('.price-display + p');
            if (roundInfoElement) {
                const currentText = roundInfoElement.textContent;
                const newText = currentText.replace(/第\d+轮/, `第${roundNumber}轮`);
                roundInfoElement.textContent = newText;
            }
        }
        
        // 初始化价格图表
        function initPriceChart() {
            try {
                console.log("开始初始化图表...");
                const canvas = document.getElementById('priceChart');
                if (!canvas) {
                    console.error("找不到Canvas元素!");
                    return null;
                }
                
                // 确保元素是Canvas
                if (!(canvas instanceof HTMLCanvasElement)) {
                    console.error("priceChart元素不是Canvas!");
                    return null;
                }
                
                const ctx = canvas.getContext('2d');
                if (!ctx) {
                    console.error("无法获取2D上下文!");
                    return null;
                }
                
                // 准备价格数据
                const priceHistory = <?php echo json_encode($price_history); ?>;
                console.log("价格历史数据:", priceHistory);
                const priceData = priceHistory.map(item => ({
                    x: new Date(item.timestamp),
                    y: parseFloat(item.price)
                }));
                
                // 准备交易数据
                const tradeDataRaw = <?php echo json_encode($trade_data); ?>;
                console.log("交易数据:", tradeDataRaw);
                
                // 简化图表配置
                const chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        datasets: [
                            {
                                label: '价格走势',
                                data: priceData,
                                borderColor: '#4caf50',
                                backgroundColor: 'rgba(76, 175, 80, 0.1)',
                                borderWidth: 2,
                                fill: false,
                                tension: 0.1
                            },
                                                    {
                            label: '交易数量',
                            data: tradeDataRaw.map(item => ({
                                x: new Date(item.time_group),
                                y: parseFloat(item.trade_quantity || 0)
                            })),
                            borderColor: '#2196F3',
                            backgroundColor: 'rgba(33, 150, 243, 0.1)',
                            borderWidth: 2,
                            fill: false,
                            tension: 0.1,
                            yAxisID: 'y1'
                        }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        scales: {
                            x: {
                                type: 'time',
                                time: {
                                    unit: 'minute',
                                    displayFormats: {
                                        minute: 'HH:mm'
                                    }
                                },
                                title: {
                                    display: true,
                                    text: '时间'
                                }
                            },
                            y: {
                                title: {
                                    display: true,
                                    text: '价格 (¥)'
                                }
                            },
                            y1: {
                                position: 'right',
                                title: {
                                    display: true,
                                    text: '交易数量'
                                },
                                grid: {
                                    drawOnChartArea: false
                                }
                            }
                        }
                    }
                });
                
                console.log("图表初始化完成!");
                window.priceChart = chart; // 保存到全局变量
                return chart;
            } catch (error) {
                console.error("图表初始化失败:", error);
                // 显示错误信息在页面上
                const chartContainer = document.querySelector('.price-chart');
                if (chartContainer) {
                    chartContainer.innerHTML = `
                        <div style="padding: 20px; text-align: center; color: red;">
                            <h3>图表加载失败</h3>
                            <p>${error.message}</p>
                            <p>请检查浏览器控制台获取更多信息</p>
                        </div>
                    `;
                }
                return null;
            }
        }
        
        // 刷新数据
        function refreshData() {
            location.reload();
        }
        
        // 页面加载完成后初始化图表
        document.addEventListener('DOMContentLoaded', function() {
            console.log("DOM加载完成，准备初始化图表...");
            
            // 添加一个简单的加载指示器
            const chartContainer = document.querySelector('.price-chart');
      
            
            // 确保Chart.js和相关依赖已加载
            if (typeof Chart === 'undefined') {
                console.error("Chart.js未加载!");
                const chartContainer = document.querySelector('.price-chart');
                if (chartContainer) {
                    chartContainer.innerHTML = `
                        <div style="padding: 20px; text-align: center; color: red;">
                            <h3>图表加载失败</h3>
                            <p>Chart.js库未能正确加载。请刷新页面重试。</p>
                        </div>
                    `;
                }
                return;
            }
            
            // 初始化图表
            const chart = initPriceChart();
            if (!chart) {
                console.error("图表初始化失败!");
                return;
            }
            
            console.log("图表已成功初始化，启动WebSocket连接...");
            
            // 启动WebSocket连接
            connectWebSocket();
            
            // 备用：每30秒自动刷新数据（当WebSocket不可用时）
            setInterval(function() {
                try {
                    console.log("开始获取最新数据...");
                    fetch('ajax/get_price_stats.php')
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`HTTP错误! 状态: ${response.status}`);
                            }
                            return response.json();
                        })
                        .then(data => {
                            console.log("收到数据:", data);
                            if (data.success) {
                                // 更新价格显示
                                document.querySelector('.price-display').innerHTML = 
                                    `¥${parseFloat(data.current_price).toFixed(2)}
                                    <span class="trend-indicator trend-${data.trend}">
                                        ${data.trend === 'up' ? '上涨' : (data.trend === 'down' ? '下跌' : '随机')}
                                        (${data.strength}%)
                                    </span>`;
                                
                                // 更新价格数据
                                chart.data.datasets[0].data = data.price_history.map(item => ({
                                    x: new Date(item.timestamp),
                                    y: parseFloat(item.price)
                                }));
                                
                                // 更新交易数据
                                if (data.trade_data && data.trade_data.length > 0) {
                                    chart.data.datasets[1].data = data.trade_data.map(item => ({
                                        x: new Date(item.time_group),
                                        y: parseFloat(item.trade_quantity || 0)
                                    }));
                                }
                                
                                chart.update();
                                console.log("图表数据已更新");
                            } else {
                                console.error("获取数据失败:", data.message);
                            }
                        })
                        .catch(error => {
                            console.error('更新数据失败:', error);
                        });
                } catch (error) {
                    console.error("刷新数据时出错:", error);
                }
            }, 30000);
        });
        
        // 价格区间实时预览
        function updateRangePreview() {
            const minPrice = parseFloat(document.getElementById('min-price').value) || 0;
            const maxPrice = parseFloat(document.getElementById('max-price').value) || 0;
            
            // 更新预览显示
            const rangePreview = document.getElementById('range-preview');
            const rangeWidth = document.getElementById('range-width');
            
            if (minPrice > 0 && maxPrice > minPrice) {
                rangePreview.textContent = `¥${minPrice.toFixed(2)} - ¥${maxPrice.toFixed(2)}`;
                rangeWidth.textContent = `¥${(maxPrice - minPrice).toFixed(2)}`;
                rangeWidth.parentElement.style.color = '#4caf50';
            } else {
                rangePreview.textContent = '无效区间';
                rangeWidth.textContent = '请输入有效价格';
                rangeWidth.parentElement.style.color = '#f44336';
            }
            
            // 验证最大价格输入
            const maxPriceInput = document.getElementById('max-price');
            if (minPrice > 0) {
                maxPriceInput.min = (minPrice + 0.01).toFixed(2);
            }
        }
        
        // 绑定价格输入事件
        document.addEventListener('DOMContentLoaded', function() {
            const minPriceInput = document.getElementById('min-price');
            const maxPriceInput = document.getElementById('max-price');
            
            if (minPriceInput && maxPriceInput) {
                minPriceInput.addEventListener('input', updateRangePreview);
                maxPriceInput.addEventListener('input', updateRangePreview);
                
                // 初始化预览
                updateRangePreview();
            }
        });
    </script>
</body>
</html>
